import React, {Component,useState,useRef} from 'react';
import PropTypes from 'prop-types';
import { List, Avatar ,Table, Tag, Space,Button,Modal,
    Form, Input, Row ,Col, Checkbox ,Tabs, Typography, Divider,Select,message} from 'antd';
import {getForms,getForm} from "../api/formManagement";
import  {saveDimMember,validateMemberFormula}  from  '../api/dim'
import SelectMemberForFormula from './selectMemberForFormula.js'
import MultiChoice from './MultiChoice.js'
export default class Dim_Info extends Component {

    constructor(props) {
        super(props)
        this.state = {
        }
    }

    closeSelf=()=>{
        this.props.onCancel();
    }

    confirm=()=>{
      //  this.props.handleSave(_v);
    }

    onChange = (e) => {
       // this.setState({ radioValue: e.target.value })
    }

    onChangeFormtName = (e) => {

    }

    onChangeAtReportDesc = (e) => {
        // this.setState({ radioValue: e.target.value })
    }

    componentWillReceiveProps(nextProps){


    }


    handleChange(value) {

    }

    getLayoutMbrs = (props) => {


    }

    render() {



        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
        };


        // const { TabPane } = Tabs;

        const radioStyle = {
            display: 'block',
            height: '30px',
            lineHeight: '30px',
        };

        // function callback(key) {
        //     console.log(key);
        // }


        const onChange = e => {
        };

        const onChangeAtInputNo=(value)=> {
            console.log('changed', value);
        }

        function handleChangeAtCurrency(value) {
            //console.log(`selected ${value}`);
        }

        function handleOk() {
            console.log("==============handleOk==================")
            //formRef.submit();

        }


        return (
            <>
                <Modal
                    width={840}
                    height={800}
                    title="添加子代"
                    visible={this.props.visible}
                    confirmLoading={this.props.confirmLoading}

                    cancelText='返回'
                    onCancel={this.props.onCancel}
                    //onOk={handleOk}
                    footer={null}
                    destroyOnClose
                    maskClosable={false}
                >
                    <DimForm alias={this.props.alias}
                             datastores={this.props.datastores}
                             account_type={this.props.account_type}
                             balance_type={this.props.balance_type}
                             data_store_types={this.props.data_store_types}
                             cubes={this.props.cubes}
                             operations={this.props.operations}
                             onCancel={this.props.onCancel}
                             dimId={this.props.dimId}
                             dims={this.props.dims}
                             selectedRows={this.props.selectedRows}
                             flg={this.props.flg}
                             mbrName={this.props.mbrName}
                             formulaTxt={this.props.formulaTxt}
                    />
                </Modal>


            </>
        );
    }

}

const styles = {
    focus: {
        width: '20px',
        opacity: 1
    },


    box:{
    display: 'flex',
    flexDirection: 'row'
    }
}




//Form表单 begin
//const { Option } = Select;
const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 16,
    },
};
const tailLayout = {
    wrapperCol: {
        offset: 8,
        span: 16,
    },
};

const DimForm = (prop) => {
    const childRef = useRef();
   // const  [visible, setVisible] =  useState(false);
    const  [isModalVisible, setIsModalVisible] =  useState(false);
    const  [seleectedDim, setSeleectedDim] =  useState(prop.dims[0].id);   //公式编辑--选择维度 如 111 112 1113 etc
    const [dimId,setDimId]=useState(prop.dimId);  //维度！！！
    const  [mbrName, setMbrName] =  useState(prop.mbrName);  //成员名称
    const  [formulaTxt, setFormulaTxt] =  useState(prop.formulaTxt);  //成员名称


    const { Option } = Select;
    //const alias=prop.alias;
    const [form] = Form.useForm();


    const onGenderChange_Dim = (value) => {
        if(value!=null || value!=""||value!=undefined){
            setSeleectedDim(value) ;
        }
    };




    const onFinish = (values) => {
        let _member={...values,
            dimId:dimId,
            parentMemberId: prop.selectedRows[0].id,
            memberId:"",
            flg: prop.flg,
        };


        saveDimMember(_member).then(
            (res) => {
                message.success('success');
                //调用关闭
                prop.onCancel();
            },
            (error) => {
                console.log("get response failed!");
            }
        );
    };

    const onReset = () => {
        form.resetFields();
    };


    const callback = (key) => {
        console.log(key);
    }

    const { TabPane } = Tabs;

    const { Title } = Typography;
    const { TextArea } = Input;

    const onFill = () => {
        form.setFieldsValue({
            note: 'Hello world!',
            gender: 'male',
        });
    };
    //打开选择窗体
    const  openSelModal=()=>{
        if(seleectedDim==-1){
            message.info("请选择维度")
            return;
        }
        setIsModalVisible(true)
    }

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = () => {
        //childRef.current.changeVal(99);
        let  r=childRef.current.getSelectedMember();
        console.log("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"+r)
        let addStr="";

        if(r.length>0){     //>0
            for(let i in r){
                addStr+=r[i].navigation+"\n"
            }
        }

        let memberFormulaContenttxt=form.getFieldValue("memberFormulaContent");
        if(memberFormulaContenttxt==undefined) memberFormulaContenttxt="";

        memberFormulaContenttxt+=addStr;
        form.setFieldsValue({memberFormulaContent:memberFormulaContenttxt})

        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    //验证公式
    const validateFormula=()=>{
        //获取formulaText
        let formulaText=form.getFieldValue("memberFormulaContent");
        if(formulaText==undefined) formulaText="";
        if(formulaText==null||formulaText.trim()==""){
            message.info("公式为空");
            return;
        }



        //let dimId=dimId;

        validateMemberFormula(formulaText,dimId).then(
            (res) => {
                message.info(res.msg);
            },
            (error) => {
                //message.info(res.msg);
            }
        );
    }

    var arr = [1, 2, 3];
    let p=-1;
    return <>
        <Form {...layout}

              form={form}
              name="control-hooks"
              initialValues={{
                  //dimId: prop.dimId,
                  memberName: prop.mbrName,   //需要录入的member name
                  memberFormulaContent:prop.formulaTxt,
                  //parentMemberId: prop.selectedRows[0].id,  //可能是父节点 就是说选中的维度树当中的节点
                  //flg: prop.flg,
                  operations1:prop.operations[0][0],  // 其实 operations1 是动态出来的 完全应该用form list来弄 可能更合适
                  dataStore:prop.datastores[0][0],     //数据存储
                  accountType:prop.account_type[0][0],  //科目类型
                  blanceType: prop.balance_type[0][0], //余额类型
                  dataType:prop.data_store_types[0][0],
              }}
              onFinish={onFinish}>

            {/*<Tabs defaultActiveKey="1" onChange={callback}>*/}
                {/*<TabPane tab="成员属性" key="1">*/}
                    {/*<Form.Item*/}
                        {/*name="dimId"*/}
                        {/*label=""*/}
                        {/*hidden={true}*/}
                    {/*/>*/}

                    {/*<Form.Item*/}
                        {/*name="parentMemberId"*/}
                        {/*label=""*/}
                        {/*hidden={true}*/}
                    {/*/>*/}


                    {/*<Form.Item*/}
                        {/*key="memberId"*/}
                        {/*label=""*/}
                        {/*hidden={true}*/}
                    {/*/>*/}

                    {/*<Form.Item*/}
                        {/*key="flg"*/}
                        {/*label=""*/}
                        {/*hidden={true}*/}
                    {/*/>*/}


                    <Form.Item
                        name="memberName"
                        label="名称"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="aliasTable"
                        label="别名表"
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Select
                            placeholder="Select a option and change input text above"
                            // onChange={onGenderChange}
                            allowClear
                        >
                            {
                                prop.alias.map((item, index) => {
                                    return (
                                        <Option value={item.id} key={"alias" + index}>{item.name}</Option>
                                    )
                                })
                            }

                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="aliasTxt"
                        label="别名表值"
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        name="description"
                        label="说明"
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>
                    {
                        prop.cubes.map((item, index) => {
                            return (

                                <Form.Item
                                            name={"cubes" + (index + 1)}
                                            key={"cubes" + (index + 1)}
                                           label={"模型" + (index + 1)}>
                                    <Row>
                                        <Col span={4}>
                                            <Checkbox
                                                checked={true}
                                                id={"cb" + item.id}
                                                key={"cb" + item.id}
                                                style={{
                                                    lineHeight: '32px',
                                                }}
                                            >
                                            </Checkbox>
                                        </Col>

                                        <Col span={16}></Col>

                                        <Col span={4}>
                                            <Form.Item
                                                name={"operations" + (index + 1)}
                                                key={"operations" + (index + 1)}
                                                label=""
                                                rules={[
                                                    {
                                                        required: false,
                                                    },
                                                ]}
                                            >
                                                <Select
                                                    placeholder="Select a option and change input text above"
                                                    // onChange={onGenderChange}
                                                    //allowClear

                                                >
                                                    {
                                                        prop.operations.map((item) => {
                                                            return (
                                                                <Option value={item[0]}
                                                                        key={"operations" + item[0]}>{item[1]}</Option>
                                                            )
                                                        })
                                                    }
                                                </Select>
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form.Item>

                            )


                        })
                    }

                    {/*/end/模型*/}
                    <Form.Item
                        name="dataStore"
                        label="数据存储："
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Select
                            placeholder="Select a option and change input text above"
                            // onChange={onGenderChange}
                            allowClear
                        >
                            {
                                prop.datastores.map(item => {
                                    return (
                                        <Option value={item[0]} key={"ds" + item[0]}>{item[1]}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="accountType"
                        label="科目类型："
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Select
                            placeholder="Select a option and change input text above"
                            // onChange={onGenderChange}
                           /// allowClear
                           // defaultValue={111}
                        >
                            {
                                prop.account_type.map(item => {
                                    return (
                                        <Option value={item[0]} key={"account_type" + item[0]}>{item[1]}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="blanceType"
                        label="余额类型："
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Select
                            placeholder="Select a option and change input text above"
                            // onChange={onGenderChange}
                            allowClear
                        >
                            {
                                prop.balance_type.map(item => {
                                    return (
                                        <Option value={item[0]} key={"balance_type" + item[0]}>{item[1]}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>


                    <Form.Item
                        name="dataType"
                        label="数据类型："
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >
                        <Select
                            placeholder="Select a option and change input text above"
                            // onChange={onGenderChange}
                            allowClear
                        >
                            {
                                prop.data_store_types.map(item => {
                                    return (
                                        <Option value={item[0]} key={"data_type" + item[0]}>{item[1]}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                {/*</TabPane>*/}
                {/*<TabPane tab="成员公式" key="2">*/}
                    {/*<Title level={5}>请输入成员公式 ：（注意：请勿使用双引号；请勿添加额外的结尾符） </Title>*/}
                    <Row justify={"end"}>
                        {/*<Col span={8}></Col>*/}

                        {/*<Col span={16}>*/}
                        <Select
                            placeholder=""
                            onChange={onGenderChange_Dim}
                            //allowClear
                            size={"middle"}
                            defaultValue={prop.dims[0].id}
                        >
                            {
                                prop.dims.map((item, index) => {
                                    return (
                                        <Option value={item.id} key={"f" + index}>{item.name}</Option>
                                    )
                                })
                            }
                        </Select>
                        <Button onClick={openSelModal}>add</Button>

                        <Modal title="维度管理-选择成员"
                               zIndex={1200}
                               width={800}
                               destroyOnClose
                               visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                            <MultiChoice  ref={childRef} seleectedDim={seleectedDim}/>
                        </Modal>


                        {/*</Col>*/}
                    </Row>

                    <Row>
                        <Col span={24}>
                            <Form.Item
                                name="memberFormulaContent"
                                label="成员公式"
                                rules={[
                                    {
                                        required: false,
                                    },
                                ]}
                            >
                                <TextArea rows={8} size={"large"}/>
                            </Form.Item>
                        </Col>


                    </Row>

                    <Row>
                        <Col span={20}></Col>
                        <Col span={4}>
                            <Button onClick={validateFormula}>验证成员公式</Button>
                        </Col>
                    </Row>
                {/*</TabPane>*/}

            {/*</Tabs>*/}
            <Form.Item {...tailLayout}>

                <Button type="primary" htmlType="submit">
                    Submit
                </Button>
                <Button htmlType="button" onClick={onReset}>
                    Reset
                </Button>
            </Form.Item>
        </Form>
        {/*<SelectMemberForFormula*/}
        {/*visiable={visible}*/}

        {/*/>*/}
        <Modal/>


    </>;
};

//选择维度成员，
const selectMemberElemnet=()=>{




}

//end Form表单

//成员公式  弃用
// const MemberFormula= (prop) => {
//     const { Title } = Typography;
//     const { Option } = Select;
//     const { TextArea } = Input;
//     return (
//         <>
//             <Title level={5}>请输入成员公式 ：（注意：请勿使用双引号；请勿添加额外的结尾符） </Title>
//             <Row>
//                 <Select
//                     placeholder="Select a option and change input text above"
//                     // onChange={onGenderChange}
//                     allowClear
//                 >
//                           {
//                         prop.dims.map((item,index)=>{
//                             return (
//                                 <Option value={ item.id } key={ "f"+index }>{ item.name }</Option>
//                             )
//                         })
//                     }
//                 </Select>
//                 <Button onClick={}>add</Button>
//             </Row>
//             <TextArea rows={4}/>
//             <Button>验证成员公式</Button>
//
//
//
//
//
//         </>
//
//
//     );
//
//
//
//
// }



